<template>
  <div class="container animate__animated animate__fadeIn">
    <div class="upload-box">
      <a-upload
        list-type="picture-card"
        multiple
        :file-list="fileList"
        @preview="handlePreview"
        @change="handleChange"
        :before-upload="beforeUpload"
      >
        <div v-if="fileList.length < 6">
          <a-icon type="plus" />
          <div class="ant-upload-text">选择图片</div>
        </div>
      </a-upload>
      <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </div>
    <a-form-model ref="form" :model="formData" :rules="rules">
      <a-form-model-item
        label="标题"
        prop="title"
        :labelCol="{ span: 2 }"
        :wrapperCol="{ span: 22 }"
      >
        <a-input
          v-model="formData.title"
          placeholder="请输入标题！"
          style="width: 500px"
        />
      </a-form-model-item>
      <a-form-model-item
        label="宠物类型"
        :labelCol="{ span: 2 }"
        :wrapperCol="{ span: 22 }"
      >
        <a-select
          style="width: 150px"
          placeholder="请输入宠物类型"
          v-model="formData.petType"
        >
          <a-select-option v-for="i in ['猫', '狗', '兔', '其他']" :key="i">
            {{ i }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item
        label="宠物性别"
        :labelCol="{ span: 2 }"
        :wrapperCol="{ span: 22 }"
      >
        <a-radio-group
          :options="[
            { label: '雄性', value: 1 },
            { label: '雌性', value: 2 },
          ]"
          :default-value="1"
          v-model="formData.petSex"
        />
      </a-form-model-item>
      <a-form-model-item
        label="宠物年龄"
        :labelCol="{ span: 2 }"
        :wrapperCol="{ span: 22 }"
      >
        <a-input-number
          id="inputNumber"
          v-model="formData.petMonth"
          :min="0"
          :max="360"
        />&nbsp;个月&nbsp;&nbsp;
      </a-form-model-item>
      <a-form-model-item
        prop="linkman"
        label="联系人"
        :labelCol="{ span: 2 }"
        :wrapperCol="{ span: 22 }"
      >
        <a-input
          v-model="formData.linkman"
          placeholder="请输入联系人"
          style="width: 200px"
        />
      </a-form-model-item>
      <a-form-model-item
        prop="wechat"
        label="微信号"
        :labelCol="{ span: 2 }"
        :wrapperCol="{ span: 22 }"
      >
        <a-input
          v-model="formData.wechat"
          placeholder="请输入微信号"
          style="width: 200px"
        />
      </a-form-model-item>
      <a-form-model-item
        prop="phone"
        label="联系电话"
        :labelCol="{ span: 2 }"
        :wrapperCol="{ span: 22 }"
      >
        <a-input
          v-model="formData.phone"
          placeholder="请输入联系电话"
          style="width: 200px"
        />
      </a-form-model-item>
      <a-form-model-item
        prop="address"
        label="领养地址"
        :labelCol="{ span: 2 }"
        :wrapperCol="{ span: 22 }"
      >
        <a-input
          v-model="formData.address"
          placeholder="请输入地址"
          style="width: 500px"
        />
      </a-form-model-item>
      <a-form-model-item
        prop="description"
        label="详细描述"
        :labelCol="{ span: 2 }"
        :wrapperCol="{ span: 22 }"
      >
        <a-textarea
          v-model="formData.description"
          placeholder="请详细描述一下你的宠物吧！"
          :auto-size="{ minRows: 3, maxRows: 5 }"
          style="width: 600px"
        />
      </a-form-model-item>
      <a-form-model-item :labelCol="{ span: 2 }" :wrapperCol="{ span: 22 }">
        <button class="public-btn" @click="submit">确认发布</button>
      </a-form-model-item>
    </a-form-model>
  </div>
</template>

<script>
import requests from "../js/requests.js";
import {
  Upload,
  Icon,
  Modal,
  Input,
  Select,
  Radio,
  InputNumber,
  FormModel,
} from "ant-design-vue";

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}

export default {
  name: "PublicFosterage",
  components: {
    AUpload: Upload,
    AIcon: Icon,
    AModal: Modal,
    AInput: Input,
    ASelect: Select,
    ASelectOption: Select.Option,
    ARadioGroup: Radio.Group,
    AInputNumber: InputNumber,
    ATextarea: Input.TextArea,
    AFormModel: FormModel,
    AFormModelItem: FormModel.Item,
  },
  data() {
    return {
      previewVisible: false,
      previewImage: "",
      fileList: [],
      files: [],
      onceTip: null, // 多选图片时如果某张图片不符合要求会提示多次。这里存一个计时器进行防抖，在handleChange函数使用
      formData: {
        title: "",
        petType: "猫",
        petSex: 1,
        petMonth: 0,
        linkman: "",
        wechat: "",
        phone: "",
        address: "",
        description: "",
      },
      rules: {
        title: [
          { required: true, message: "请输入标题！", trigger: "change" },
          { max: 100, message: "长度不能超过100个字符！", trigger: "change" },
        ],
        linkman: [
          { required: true, message: "请输入联系人！", trigger: "change" },
          { max: 32, message: "长度不能超过32个字符！", trigger: "change" },
        ],
        wechat: [
          { required: true, message: "请输入微信号！", trigger: "change" },
          { max: 32, message: "长度不能超过32个字符！", trigger: "change" },
        ],
        phone: [
          { max: 32, message: "长度不能超过32个字符！", trigger: "change" },
        ],
        address: [
          { max: 100, message: "长度不能超过100个字符！", trigger: "change" },
        ],
        description: [
          { max: 1000, message: "长度不能超过1000个字符！", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange({ fileList }) {
      let isList6 = fileList.length <= 6;
      let isJpgOrPng = true;
      let isLt5M = true;
      console.log(fileList);
      for (let i = 0; i < fileList.length; i++) {
        if (
          fileList[i].originFileObj.type !== "image/jpeg" &&
          fileList[i].originFileObj.type !== "image/png" &&
          fileList[i].originFileObj.type !== "image/webp"
        ) {
          isJpgOrPng = false;
          break;
        }
        if (fileList[i].originFileObj.size > 1024 * 1024 * 5) {
          isLt5M = false;
          break;
        }
      }

      // 进行防抖，防止多选图片时，图片不符合要求会进行多次提示
      if (this.onceTip) {
        clearTimeout(this.onceTip);
      }
      this.onceTip = setTimeout(() => {
        if (!isList6) {
          this.$message.error("最多上传六张图片!");
        }
        if (!isJpgOrPng) {
          this.$message.error("只能上传jpeg、png或webp类型的图片!");
        }
        // const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isLt5M) {
          this.$message.error("单张图片不能大于5MB!");
        }
      }, 100);

      if (isJpgOrPng && isLt5M && isList6) {
        this.fileList = fileList;
        let i = 0;
        fileList.forEach((file) => {
          this.files[i++] = file.originFileObj;
        });
      }
    },
    beforeUpload() {
      return false;
    },
    submit() {
      let that = this;
      Modal.confirm({
        title: "您确定要发布这这条寄养消息吗？",
        content:
          "发布寄养消息时请注意联系方式是否正确，如果不正确别人将无法联系到你。",
        okText: "确认",
        cancelText: "取消",
        onOk() {
          if (that.files.length == 0) {
            that.$message.warning("您忘记上传图片了哦！");
          } else {
            that.$refs.form.validate((valid) => {
              if (valid) {
                let formData1 = new FormData();
                that.files.forEach((file) => {
                  formData1.append("files", file);
                });
                formData1.append("data", JSON.stringify(that.formData));
                requests.publicFosterage(formData1).then((res) => {
                  if (res.code == 200) {
                    that.$message.success(res.msg);
                  } else {
                    that.$message.error(res.msg);
                  }
                });
              }
            });
          }
        },
        onCancel() {},
      });
    },
  },
};
</script>

<style scoped>
.container {
  width: 100%;
  padding-top: 30px;
  padding-left: 50px;
}

.container > div {
  margin: 20px 0;
}

.upload-box {
  width: 100%;
  height: 110px;
  display: flex;
  /* background-color: aliceblue; */
}

/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.public-btn {
  padding: 3px 5px;
  margin-right: 100px;
  float: right;
  color: rgb(255, 255, 255);
  border: none;
  border-radius: 5px;
  background-color: rgb(245, 61, 61);
  transition: 0.3s;
}

.public-btn:hover {
  box-shadow: 0 5px 10px rgb(0, 0, 0, 0.5);
}
</style>